<template>
  <div class="cost-container">
    <a-card class="cost-card" :bordered="false">
      <!-- 顶部标题和操作区 -->
      <div class="header-section">
        <h2 class="page-title">行车费用管理</h2>
        <div class="table-operations">
          <a-row :gutter="16" align="middle">
            <a-col :span="8">
              <a-input-search
                v-model:value="search"
                placeholder="搜索费用记录..."
                @search="fetchCostList"
                enter-button
                size="large"
                class="search-input"
              />
            </a-col>
            <a-col :span="16" style="text-align: right">
              <a-button type="primary" size="large" @click="showAddModal" class="add-button">
                <plus-outlined />
                新增费用记录
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>

      <!-- 费用记录表格 -->
      <a-table
        :columns="columns"
        :data-source="costList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        class="custom-table"
        :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : '')"
      >
        <!-- 自定义列显示 -->
        <template v-slot:bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'applyName'">
            <div class="trip-info">
              <car-outlined class="info-icon" />
              {{record.applyName}}
            </div>
          </template>
          <template v-if="column.dataIndex === 'licensePlate'">
            <div class="trip-info">
              <car-outlined class="info-icon" />
              {{record.licensePlate}}
            </div>
          </template>
          <template v-if="column.dataIndex === 'costType'">
            <a-tag :color="getCostTypeColor(record.costType)">
              {{ getCostTypeName(record.costType) }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'cost'">
            <span class="cost-amount">
              ¥{{ record.cost.toFixed(2) }}
            </span>
          </template>
          <template v-if="column.dataIndex === 'applyTime'">
              <span class="date-text">
                {{ record.applyTime ? dayjs(record.applyTime).format('YYYY-MM-DD HH:mm:ss') : '--' }}
              </span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" @click="showEditModal(record)" class="edit-button">
                <edit-outlined />
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这条费用记录吗？"
                @confirm="handleDelete(record.costId)"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button type="link" danger class="delete-button">
                  <delete-outlined />
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 添加/编辑费用记录模态框 -->
      <a-modal
        :title="modalTitle"
        :open="modalVisible"
        @ok="handleModalOk"
        @cancel="handleModalCancel"
        class="cost-modal"
        :maskClosable="false"
        :width="500"
      >
        <a-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-form-item label="申请人" name="applyName">
            <a-input
              v-model:value="formData.applyName"
              placeholder="请输入申请人"
              show-search
           />
          </a-form-item>
          <a-form-item label="车牌号" name="licensePlate">
            <a-input
                v-model:value="formData.licensePlate"
                placeholder="请输入车牌号"
                show-search
            />
          </a-form-item>
          <a-form-item label="费用类型" name="costType">
            <a-select
              v-model:value="formData.costType"
              placeholder="请选择费用类型"
              class="custom-select"
            >
              <a-select-option :value="1">
                <car-outlined style="margin-right: 8px" />加油费
              </a-select-option>
              <a-select-option :value="2">
                <tool-outlined style="margin-right: 8px" />维修费
              </a-select-option>
              <a-select-option :value="3">
                <environment-outlined style="margin-right: 8px" />停车费
              </a-select-option>
              <a-select-option :value="4">
                <more-outlined style="margin-right: 8px" />其他费用
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="费用金额" name="cost">
            <a-input-number
              v-model:value="formData.cost"
              :min="0"
              :precision="2"
              style="width: 100%"
              placeholder="请输入费用金额"
              class="custom-input-number"
              prefix="¥"
            />
          </a-form-item>
          <a-form-item label="申请时间" name="applyTime">
            <a-date-picker
              v-model:value="formData.applyTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择申请时间"
              class="custom-date-picker"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, CarOutlined, EditOutlined, DeleteOutlined, ToolOutlined, EnvironmentOutlined, MoreOutlined } from '@ant-design/icons-vue'
import { list, add, del, update } from '@/api/cost'
import { list as getTripList} from '@/api/trip'
import { getDataList } from '@/api/data'
import dayjs from "dayjs";
// 表格列定义
const columns = [
  {
    title: '申请人',
    dataIndex: 'applyName',
    key: 'applyName',
  },
  {
    title: '车牌号',
    dataIndex: 'licensePlate',
    key:'licensePlate'
  },
  {
    title: '费用类型',
    dataIndex: 'costType',
    key: 'costType',
  },
  {
    title: '费用金额',
    dataIndex: 'cost',
    key: 'cost',
    customRender: ({ text }) => `¥${text.toFixed(2)}`
  },
  {
    title: '申请时间',
    dataIndex: 'applyTime',
    key: 'applyTime',
    customRender: ({ text }) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '--'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
  },
]

// 数据相关
const loading = ref(false)
const costList = ref([])
const tripList = ref([])
const getDriverList=ref([])
const getVehicleList=ref([])
const getUserList=ref([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
})
const search = ref('')

// 模态框相关
const modalVisible = ref(false)
const modalTitle = ref('添加费用记录')
const formRef = ref(null)
const formData = ref({
  userId:'',
  applyName:'',
  licensePlate:'',
  costType: '',
  cost: '',
  applyTime:''
})

// 表单验证规则
const rules = {
  applyName: [
    { required: true, message: '请输入申请人', trigger: 'change' }
  ],
  costType: [
    { required: true, message: '请选择费用类型', trigger: 'change' }
  ],
  cost: [
    { required: true, message: '请输入费用金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '费用金额必须大于0', trigger: 'blur' }
  ]
}

// 获取费用类型名称
const getCostTypeName = (type) => {
  const types = {
    1: '加油费',
    2: '维修费',
    3: '停车费',
    4: '其他费用'
  }
  return types[type] || '未知类型'
}

// 获取出车记录信息
const getTripInfo = (tripId) => {
  const trip = tripList.value.find(t => t.tripId === tripId)
  if (!trip) return '-'
  return `${getUserName(trip.userId)},${getVehicleName(trip.vehicleId)},${trip.usageTime}`
}
const getDriverName = (driverId) => {
    const driver = getDriverList.value.find(dr => dr.driverId === driverId)
    return driver ? driver.name : '-'
}
const getUserName = (userId) => {
  const user = getUserList.value.find(u => u.userId === userId)
  return user ? user.username : '-'
}
const getVehicleName = (vehicleId) => {
    const vehicle = getVehicleList.value.find(v => v.vehicleId === vehicleId)
    return vehicle ? vehicle.licensePlate : '-'
  }

  const DataList=async()=>{
        const res =await getDataList();
        console.log(res)
        if(res.code===200){
            getVehicleList.value=res.data.vehicleInfoList
            getDriverList.value=res.data.driverInfoList
            getUserList.value=res.data.userInfoList
        }
  }
// 获取费用列表
const fetchCostList = async () => {
  loading.value = true
  try {
    const res = await list({
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
      search: search.value
    })
    costList.value = res.data.records
    pagination.value.total = res.data.total
  } catch (error) {
    message.error('获取费用列表失败')
  } finally {
    loading.value = false
  }
}

// 获取出车记录列表
const fetchTripList = async () => {
  try {
    const res = await getTripList({
      pageNum: 1,
      pageSize: 1000 // 获取较多记录用于下拉选择
    })
    tripList.value = res.data.records
  } catch (error) {
    message.error('获取出车记录失败')
  }
}

// 表格分页变化
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchCostList()
}

// 显示添加模态框
const showAddModal = () => {
  modalTitle.value = '添加费用记录'
  formData.value = {
    userId:'',
    applyName: '',
    licensePlate:'',
    costType: '',
    cost: '',
    applyTime:''
  }
  modalVisible.value = true
}

// 显示编辑模态框
const showEditModal = (record) => {
  modalTitle.value = '编辑费用记录'
  formData.value = {
    ...record ,
    applyTime: record.applyTime ? dayjs(record.applyTime) : null,
  }
  modalVisible.value = true
}

// 处理模态框确认
const handleModalOk = () => {
  formRef.value?.validate().then(async () => {
    try {
      const submitData = {
        ...formData.value,
        applyTime: formData.value.applyTime ? formData.value.applyTime.format('YYYY-MM-DD HH:mm:ss') : null,
      }
      const res = formData.value.costId 
        ? await update(submitData)
        : await add(submitData)

      if(res.code === 200) {
        message.success(`${modalTitle.value}成功`)
        modalVisible.value = false
        fetchCostList()
      }
    } catch (error) {
      message.error(`${modalTitle.value}失败`)
    }
  })
}

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 处理删除费用记录
const handleDelete = async (costId) => {
  try {
    const res = await del(costId)
    if(res.code === 200) {
      message.success('删除成功')
      fetchCostList()
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 添加费用类型颜色映射
const getCostTypeColor = (type) => {
  const colors = {
    1: 'blue',    // 加油费
    2: 'orange',  // 维修费
    3: 'green',   // 停车费
    4: 'purple'   // 其他费用
  }
  return colors[type] || 'default'
}

// 添加出车记录筛选方法
const filterTripOption = (input, option) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 页面加载时获取数据
onMounted(() => {
  fetchCostList()
  fetchTripList()
  DataList()
})
</script>

<style scoped>
.cost-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.cost-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.header-section {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  color: #1f1f1f;
  margin-bottom: 24px;
  font-weight: 500;
}

.search-input {
  width: 100%;
  :deep(.ant-input) {
    border-radius: 4px;
  }
}

.add-button {
  border-radius: 4px;
  height: 40px;
  font-weight: 500;
}

.custom-table {
  :deep(.ant-table-thead > tr > th) {
    background: #fafafa;
    font-weight: 500;
  }
  
  :deep(.table-striped) {
    background-color: #fafafa;
  }
}

.trip-info {
  display: flex;
  align-items: center;
  .info-icon {
    margin-right: 8px;
    color: #1890ff;
  }
}

.cost-amount {
  font-family: 'Roboto Mono', monospace;
  font-weight: 500;
  color: #52c41a;
}

.edit-button {
  color: #1890ff;
}

.delete-button {
  color: #ff4d4f;
}

.cost-modal {
  :deep(.ant-modal-header) {
    border-bottom: 1px solid #f0f0f0;
    padding: 16px 24px;
  }
  
  :deep(.ant-modal-footer) {
    border-top: 1px solid #f0f0f0;
    padding: 16px 24px;
  }
}

.custom-select {
  width: 100%;
}

.custom-input-number {
  width: 100%;
  :deep(.ant-input-number-handler-wrap) {
    background-color: #fafafa;
  }
}

/* 添加一些动画效果 */
.add-button,
.edit-button,
.delete-button {
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-1px);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .cost-container {
    padding: 12px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .header-section {
    margin-bottom: 16px;
  }
}
</style>